<template>
    <div v-loading="loading" element-loading-text="拼命加载中..." class="app-container">
        <el-page-header v-if="showPageHeader" class="box-shadow mb-3" icon="arrow-left" @back="handleGoBack">
            <template #content>
                <span>商务人员操作</span>
            </template>
            <template #extra>
                <div class="flex items-center">
                    <el-button icon="arrow-left" @click="handleGoBack">返回上页</el-button>
                    <!-- <el-button icon="edit" type="primary" @click="onSubmitForm">保存修改</el-button> -->
                </div>
            </template>
        </el-page-header>

        <div class="app-container-main">
            <el-row :gutter="12">
                <el-col :md="12">
                    <el-card class="content-card">
                        <div class="el-descriptions__header">
                            <div class="el-descriptions__title">基本信息</div>
                        </div>
                        <el-form ref="formRef" :disabled="readonly" :model="formData" :rules="formRules"
                            label-width="120px">
                            <el-form-item label="商务姓名：" prop="name">
                                <el-input v-model="formData.name" :readonly="readonly" placeholder="请输入商务姓名" />
                            </el-form-item>

                            <el-form-item label="联系电话：" prop="phone">
                                <el-input v-model="formData.phone" :readonly="readonly" placeholder="请输入联系电话" />
                            </el-form-item>
                        </el-form>
                    </el-card>
                </el-col>
            </el-row>

            <el-row :gutter="12">
                <el-col :md="24">
                    <el-card class="content-card">
                        <div class="el-descriptions__header">
                            <div class="el-descriptions__title">设置费率</div>
                        </div>
                        <el-tabs v-model="activeName">
                            <el-tab-pane label="收款" name="first"></el-tab-pane>
                            <el-tab-pane label="代付" name="second" disabled></el-tab-pane>
                        </el-tabs>
                        <div class="mb-4">
                            <el-checkbox-group v-model="type" size="large" @change="handleChange">
                                <div class="mb-3">
                                    <el-checkbox label="小程序支付场景" value="tiny_app" border />
                                    <el-checkbox label="H5场景" value="wap" border />
                                    <el-checkbox label="线下当面付场景" value="offline" border />
                                </div>
                                <div class="mb-4">
                                    <el-checkbox label="APP支付场景" value="app" border />
                                    <el-checkbox label="网站支付场景" value="pc" border />
                                    <el-checkbox label="JSAPI" value="jsapi" border />
                                </div>
                            </el-checkbox-group>
                        </div>
                        <el-form ref="formRateRef" :disabled="readonly" :model="info" label-width="130px">

                            <div v-for="(item, index) in info.payee" :key="index">
                                <div>{{ item.type }}</div>
                                <el-form-item :label="'费率(%)：'" :prop="'payee.' + index + '.rate'"
                                    :rules="getValidationRules(index)">
                                    <el-input v-model="item.rate" :readonly="readonly" placeholder="请设置费率" />
                                </el-form-item>
                                <el-form-item :label="'单笔最小金额：'" :prop="'payee.' + index + '.min_amount'"
                                    :rules="getValidationRules(index)">
                                    <el-input v-model="item.min_amount" :readonly="readonly" placeholder="请输入单笔最小金额" />
                                </el-form-item>
                                <el-form-item :label="'单笔最大金额：'" :prop="'payee.' + index + '.max_amount'"
                                    :rules="getValidationRules(index)">
                                    <el-input v-model="item.max_amount" :readonly="readonly" placeholder="请输入单笔最大金额" />
                                </el-form-item>
                                <el-form-item :label="'单笔手续费：'" :prop="'payee.' + index + '.extra_charge'"
                                    :rules="getValidationRules(index)">
                                    <el-input v-model="item.extra_charge" :readonly="readonly" placeholder="请输入单笔手续费" />
                                </el-form-item>
                                <el-form-item :label="'单笔最少手续费：'" :prop="'payee.' + index + '.min_charge'"
                                    :rules="getValidationRules(index)">
                                    <el-input v-model="item.min_charge" :readonly="readonly" placeholder="请输入单笔最少手续费" />
                                </el-form-item>
                                <el-divider />
                            </div>
                        </el-form>
                    </el-card>
                </el-col>
            </el-row>
            <el-row :gutter="12">
                <el-col :md="12">
                    <el-card class="content-card">
                        <div class="el-descriptions__header">
                            <div class="el-descriptions__title">账号状态</div>
                        </div>
                        <el-form-item label="状态：">
                            <el-radio-group v-model="status">
                                <el-radio :value="1">启用</el-radio>
                                <el-radio :value="0">禁用</el-radio>
                            </el-radio-group>
                        </el-form-item>

                    </el-card>
                </el-col>
            </el-row>
        </div>
        <div class="app-container-main">
            <div style="float: right;">
                <el-button @click="handleGoBack" round>取消</el-button>
                <el-button type="primary" round @click="onSubmitForm">保存</el-button>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted , watch} from 'vue';
import { ElLoading, ElMessage, ElNotification, FormInstance, FormRules } from 'element-plus';
import { MANAGERAdd, MANAGERDetail ,MANAGERUpdate} from '@/api/api-manager';
import { useRoute, useRouter } from 'vue-router';
import { useTabsNavStore } from '@/store';
const tabsNavStore = useTabsNavStore();
const currentRoute = useRoute();
const router = useRouter();
defineOptions({name: 'manager-info'});
// Props
const props = defineProps({
    id: {
        type: Number,
        required: true
    },
    readonly: {
        type: Boolean,
        default: false
    },
    showPageHeader: {
        type: Boolean,
        default: true
    }
});

// Reactive references
const loading = ref(false);
const activeName = ref('first');
const type = ref<string[]>([]);
const formData = ref({ name: '', phone: '' });
const info = ref<Object>({}); // Adjust type as necessary
const formRef = ref<FormInstance>();
const formRateRef = ref<FormInstance>();
const status = ref<Number>(1)
const initData = async (id: number) => {
    if (!id || id <= 0) return;
    loading.value = true;
    try {
        let data = {
            id: id,
            action: 'info'
        }
        await MANAGERDetail(data).then(res => {
            status.value = res.body.status
            formData.value.name = res.body.name
            formData.value.phone = res.body.phone
            type.value = res.body.info.payee.map(item => item.type)
            const newPayee = res.body.info.payee.map(item => ({
                type: item.type,
                rate: item.info.rate,
                min_amount: item.info.min_amount,
                max_amount: item.info.max_amount,
                min_charge: item.info.min_charge,
                extra_charge: item.info.extra_charge
            }));
            info.value.payee = newPayee
        })
        // formData.value = data;
    } finally {
        loading.value = false
    }
}

// Form rules
const formRules = reactive<FormRules>({
    phone: [{ required: true, message: '联系人电话不能为空', trigger: 'blur' }],
    name: [{ required: true, message: '商务姓名不能为空', trigger: 'blur' }]
});

// Validation rules for payee info
const getValidationRules = (index: number) => {
    return [
        { required: true, message: '不能为空', trigger: 'blur' }
    ];
};
const handleChangeDf= () => {
  // 记录当前选中的类型
  const selectedTypes = new Set(types.value);
  // 确保 payee 是一个数组，然后更新 payee 列表，只保留选中的类型
  if (!info.value.trans) {
    info.value.trans = []; // 确保 payee 是一个数组
  }

  info.value.trans = info.value.trans.filter(item => selectedTypes.has(item.type));
  // 为新选中的类型添加条目
  types.value.forEach(selectedType => {
    // 检查当前类型是否已在 payee 中
    const exists = info.value.trans.some(item => item.type === selectedType);
    if (!exists) {
      info.value.trans.push({
        type: selectedType,
        rate: '',
        min_amount: '',
        max_amount: '',
        min_charge: '',
        extra_charge: '',
        fee_mode:''
      });
    }
  });
  console.log(info.value.trans)
};
// Handle change in checkbox group
// Handle change in checkbox group
const handleChange = () => {
    // 记录当前选中的类型
    const selectedTypes = new Set(type.value);

    // 确保 payee 是一个数组，然后更新 payee 列表，只保留选中的类型
    if (!info.value.payee) {
        info.value.payee = []; // 确保 payee 是一个数组
    }

    info.value.payee = info.value.payee.filter(item => selectedTypes.has(item.type));

    // 为新选中的类型添加条目
    type.value.forEach(selectedType => {
        // 检查当前类型是否已在 payee 中
        const exists = info.value.payee.some(item => item.type === selectedType);
        if (!exists) {
            info.value.payee.push({
                type: selectedType,
                rate: '',
                min_amount: '',
                max_amount: '',
                min_charge: '',
                extra_charge: ''
            });
        }
    });
};

// Handle form submission
//提交
const onSubmitForm = async () => {
    try {
        const v1 = await formRef.value?.validate();
        const v2 = await formRateRef.value?.validate();
        console.log('验证结果:', v1, v2); // 调试验证结果
        if (type.value.length <= 0) {
            ElMessage({ type: 'error', message: '请选择设置费率类型' });
            return
        }
        let payee = info.value.payee.map(item => ({
            type: item.type,
            info: {
                rate: item.rate,
                min_amount: item.min_amount,
                max_amount: item.max_amount,
                min_charge: item.min_charge,
                extra_charge: item.extra_charge
            }
        }));

        let data = {
            ...formData.value,
            status: status.value,
            info: {
                payee: payee
            }
        }
        if(props.id){
            data.id = props.id
            MANAGERUpdate(data, { action: 'update' }).then(res => {
            ElMessage({ type: 'success', message: "编辑成功"});
            initData(props.id);
            // handleGoBack()
            })
        }else{
            MANAGERAdd(data, { action: 'add' }).then(res => {
            ElMessage({ type: 'success', message: "添加成功"});
            // router.push({ path: '/manager/list' })
            handleGoBack()
        })
        }

    } catch (error) {
        console.log('校验错误:', error); // 打印校验错误
        ElMessage({ type: 'error', message: '请检查是否有必填项未完善' });
    }
};
const handleGoBack = async(refresh = false) => {
  await tabsNavStore.delView(currentRoute);
  let params = {refresh: refresh ? 1 : 0}
  await router.push({path: '/manager/list', state: {params}});
   // await router.push({ path: '/manager/list' })
   await handleReset()
}
const handleReset = async () => {
    info.value = {}
    formData.value = { name: '', phone: '' }
    status.value = 1
}
// Load initial data
onMounted(async () => {
    // await handleReset();
    await initData(props.id);
});
</script>

<style lang="scss" scoped>
.app-container-main {
    .el-form-item {
        margin-bottom: 16px !important;
    }

    :deep(.el-form-item__content) {
        max-width: 36rem;
    }

    .el-input-number {
        max-width: 10rem;
    }

    .el-descriptions__title {
        border-left: 3px solid var(--el-color-primary);
        padding-left: 10px;
        font-weight: 500;
        font-size: 14px;
        line-height: 16px;
    }
}
</style>
